<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch" label-suffix="：" label-width="100px">
      <el-form-item label="培训学校" prop="trainingSchoolId">
        <el-autocomplete v-model="queryParams.schoolName" :fetch-suggestions="querySearchAsync" placeholder="请输入内容" @select="handleSelect" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="课程名称" prop="courseName">
        <el-input v-model="queryParams.courseName" placeholder="请输入课程名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="课程分类" prop="categoryIds">
        <el-cascader v-model="categoryIds" :options="categoryOptions" :props="props" clearable filterable @change="handleChangeCategory" @keyup.enter.native="handleQuery"/>
      </el-form-item>
<!--      <el-form-item label="服务年级" prop="courseGrade">
        <el-input v-model="queryParams.courseGrade" placeholder="请输入建议服务年级：1，全校；2，指定年级" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>-->
      <el-form-item label="课程状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择状态" clearable @keyup.enter.native="handleQuery">
          <el-option v-for="(value, key) in courseStateMap" :label="value" :value="key"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['system:course:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="courseList" border stripe>
      <el-table-column label="" align="center" prop="id" width="60"/>
      <el-table-column label="封面图" align="center" prop="coverUrl">
        <template slot-scope="{row}">
          <image-preview :src="row.coverUrl" :width="30" :height="30"/>
        </template>
      </el-table-column>
      <el-table-column label="授课单位" align="center" prop="trainingSchoolName"/>
      <el-table-column label="课程名称" align="center" prop="courseName"/>
      <el-table-column label="课程分类" align="center" prop="categoryId"/>
      <el-table-column label="课程分类" align="center" prop="courseType" width="100">
        <template slot-scope="{row}">
          {{ courseTypeMap[row.courseType] }}
        </template>
      </el-table-column>
      <el-table-column label="课时单价" align="center" prop="coursePrice"/>
      <el-table-column label="课时" align="center" prop="courseHour"/>
      <el-table-column label="建议服务年级" align="center" prop="courseGrade"/>
      <el-table-column label="建议授课人数" align="center" prop="studentMin">
        <template slot-scope="{row}">
          {{ row.studentMin }}-{{ row.studentMax }}
        </template>
      </el-table-column>
      <el-table-column label="是否需要耗材" align="center" prop="needMaterial">
        <template slot-scope="{row}">
          {{ row.needMaterial ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column label="课程简介" align="center" prop="courseIntro"/>
      <el-table-column label="课程状态" align="center" prop="state" width="90">
        <template slot-scope="{row}">
          {{ courseStateMap[row.state] }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150">
        <template slot-scope="{row}">
          <el-button size="mini" type="text" icon="el-icon-search" @click="handleDetail(row)">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-document-checked" @click="handleDetail(row)" v-if="row.state === 1" v-hasPermi="['system:course:check']">审核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <!-- 添加或修改培训课程信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body :close-on-click-modal="false">
      <el-descriptions class="margin-top" :column="2" size="mini" labelClassName="label_class" contentClassName="content_class" border>
        <el-descriptions-item label="授课单位" :span="2">{{ form.trainingSchoolName }}</el-descriptions-item>
        <el-descriptions-item label="课程名称">{{ form.courseName }}</el-descriptions-item>
        <el-descriptions-item label="课程分类">{{ form.categoryId }}</el-descriptions-item>
        <el-descriptions-item label="课时单价">{{ form.coursePrice }}</el-descriptions-item>
        <el-descriptions-item label="课时">{{ form.courseHour }}</el-descriptions-item>
        <el-descriptions-item label="建议服务年级">{{ form.courseGrade }}</el-descriptions-item>
        <el-descriptions-item label="建议授课人数">{{ form.studentMin }} - {{ form.studentMax }}</el-descriptions-item>
        <el-descriptions-item label="是否需要耗材" :span="2">
          <el-descriptions :title="form.needMaterial ? '需要耗材' : '不需要耗材'" :column="1" labelClassName="label_class" contentClassName="content_class" border>
            <el-descriptions-item v-for="(material, index) in form.courseMaterials" :key="material.id" :label="'耗材'+(index + 1)">
              {{ material.materialName }}

              <el-table v-loading="loading" :data="material.specsList" :show-header="false" border stripe style="width: 100%;">
                <el-table-column align="center" prop="unitNum" width="80">
                  <template slot-scope="scope">
                    套餐{{ scope.$index }}
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="specsName"/>
                <el-table-column align="center" prop="amount" width="100" :formatter="formatterAmount"/>
              </el-table>

            </el-descriptions-item>

          </el-descriptions>
        </el-descriptions-item>
        <el-descriptions-item label="封面图" :span="2">
          <image-preview :src="form.coverUrl" :width="50" :height="50"/>
        </el-descriptions-item>
        <el-descriptions-item label="课程简介" :span="2">{{ form.courseIntro }}</el-descriptions-item>
        <el-descriptions-item label="报名须知" :span="2">{{ form.courseNotes }}</el-descriptions-item>
        <el-descriptions-item label="课程目标" :span="2">{{ form.courseTarget }}</el-descriptions-item>
        <el-descriptions-item label="大纲" :span="2">
          <el-table v-loading="loading" :data="form.courseOutlineList" border stripe>
            <el-table-column label="单元" align="center" prop="unitNum" width="100">
              <template slot-scope="{row}">
                第{{ row.unitNum }}单元
              </template>
            </el-table-column>
            <el-table-column label="单元标题" prop="unitTitle" width="300"/>
            <el-table-column label="单元目标" prop="unitTarget"/>
          </el-table>
        </el-descriptions-item>
        <el-descriptions-item label="课程状态">{{ courseStateMap[form.state] }}</el-descriptions-item>
      </el-descriptions>

      <div slot="footer" align="center" class="dialog-footer">
        <el-button type="primary" v-if="form.state === 1" @click="handlePass(form.id, 2)">审核通过</el-button>
        <el-button type="danger" v-if="form.state === 1" @click="handleNoPass(form.id, 3)">审核不通过</el-button>
        <el-button type="danger" v-else @click="cancel">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listCourse, getCourse, checkCourse} from "@/api/train/training/course";
import {courseTypeMap, courseStateMap} from "@/utils/constants";
import {listTraining} from "@/api/train/training/school";
import {listMenu} from "@/api/system/menu";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listCategory} from "@/api/basic/category";

export default {
  name: "Course",
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 培训课程信息表格数据
      courseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      courseTypeMap: Object.freeze(courseTypeMap),
      courseStateMap: Object.freeze(courseStateMap),
      categoryOptions: [],
      props: {
        value: 'id',
        label: 'categoryName'
      },
      // 查询参数
      categoryIds: [],
      queryParams: {
        trainingSchoolId: undefined,
        courseName: null,
        categoryId: null,
        courseType: null,
        courseGrade: null,
        needMaterial: null,
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
    };
  },
  created() {
    this.getList()
    this.getTreeSelect()
  },
  methods: {
    handleChangeCategory(val) {
      this.queryParams.categoryId = val[val.length - 1];
    },
    /** 查询培训课程信息列表 */
    getList() {
      this.loading = true;

      listCourse(this.queryParams).then(response => {
        this.courseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        trainingSchoolId: null,
        courseName: null,
        categoryId: null,
        courseType: null,
        coursePrice: null,
        courseHour: null,
        courseGrade: null,
        studentMin: null,
        studentMax: null,
        needMaterial: null,
        coverUrl: null,
        courseIntro: null,
        courseNotes: null,
        courseTarget: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 查询菜单下拉树结构 */
    getTreeSelect() {
      listCategory({available: 1}).then(response => {
        this.categoryOptions = [];
        const category = { id: 0, categoryName: '主类目', children: [] };
        category.children = this.handleTree(response.data, "id", "pid");
        this.categoryOptions = category.children
      });
    },
    querySearchAsync(queryString, cb) {
      this.queryParams.trainingSchoolId = undefined

      if (queryString) {
        listTraining({schoolName: queryString}).then(response => {
          let results = response.rows.map(item => {
            return {
              value: item.schoolName,
              id: item.id
            }
          });

          cb(results);
        });
      } else {
        cb([]);
      }
    },
    handleSelect(item) {
      this.queryParams.trainingSchoolId = item.id
    },
    /** 修改按钮操作 */
    handleDetail(row) {
      this.reset();
      getCourse(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "培训课程信息";
      });
    },
    handleNoPass(id, state) {
      this.$prompt('请输入审核不通过的原因？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'textarea',
        inputValidator: (value) => {
          if (!value || value.length > 300) {
            return false
          }
        },
        inputErrorMessage: '请输入审核不通过的原因，字数不超过300个！'
      }).then(({value}) => {
        checkCourse({id: id, state: state, remarks: value}).then(() => {
          this.open = false
          this.$message.success('驳回成功')
          this.getList()
        }).catch(response => {
          this.$message.error(response.data.message)
          this.open = false
        })
      })
    },
    handlePass(id, state) {
      this.$confirm('确认审核通过吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        checkCourse({id: id, state: state}).then(() => {
          this.open = false
          this.$message.success('审核通过')
          this.getList()
        }).catch(response => {
          this.$message.error(response.data.message)
          this.open = false
        })
      })
    },
    formatterAmount(row, column) {
      return row.amount + '元';
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('training/school/course/export', {
        ...this.queryParams
      }, `培训课程列表_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
